$(function(){
   $("#uploadHeaderForm").submit(upload); // 重写提交事件
});

function upload(){
    var uploadUrl = getInputValue("uploadUrl");
    $.ajax({
        url: uploadUrl,
        method: "post",
        data: new FormData($("#uploadHeaderForm")[0]),
        contentType: false, // 不要在请求头设置 contentType
        processData: false // 不要将表单中的值转为字符串
    }).done(function(json){
        if (json.code == 200){
            updateHeaderUrl(json.headerUrl);
        }
    }).fail(function(xhr, status, errorThrown){
        alert("上传头像失败");
    });

    return false; // 禁止HTML表单提交
}

function getInputValue(name){
    return $("input[name='" + name + "']").val();
}

function updateHeaderUrl(headerUrl){
    var url = CONTEXT_PATH + "/user/updateHeaderUrl";
    $.post(
        url,
        {headerUrl: headerUrl},
        function(resp){
            var data = $.parseJSON(resp);
            if (data.code == 200){
                location.reload();
            } else{
                alert("更新头像失败: " + data.msg);
            }
        }
    );
}